import {Editor, MarkdownView, Modal, Notice, Plugin} from 'obsidian';
import {Handler} from './handle';
import LocalSaveHandler from './localSave';

import { MyPluginSettings, DEFAULT_SETTINGS, MySettingTab } from "./setting"


// 插件主功能设置！！
export default class AutoUploadPlugin extends Plugin {
	settings: MyPluginSettings;
	handler: Handler


	// 异步：加载插件
	async onload() {
		await this.loadSettings();
		await this.loadHandler();

		// // 添加一条命令
		// this.addCommand({
		// 	id: 'simple-plugin-demo-command1',
		// 	name: '简单插件命令示例',
		// 	callback: () => {
		// 		new Notice(this.settings.welcomeStr);
		// 		new SampleModal(this.app).open();
		// 	}
		// });

		// 添加插件设置面板
		this.addSettingTab(new MySettingTab(this.app, this));
		this.registerEvent(
			this.app.workspace.on("editor-paste", this.customPasteEventCallback)
		);
	}

	// 卸载插件
	onunload() {

	}

	// 异步：加载设置
	async loadSettings() {
		this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
	}

	async loadHandler() {
		this.handler = new LocalSaveHandler()
	}

	// 异步：保存设置
	async saveSettings() {
		await this.saveData(this.settings);
	}

	private checkUploadAddress(): boolean {
		return typeof this.settings.uploadAddress != "undefined"
			&& this.settings.uploadAddress != null && this.settings.uploadAddress != ""
	}


	private customPasteEventCallback = async (
		e: ClipboardEvent,
		_: Editor,
		markdownView: MarkdownView
	) => {

		const { files } = e.clipboardData;
		if (files.length === 0 || !files[0].type.startsWith("image")) {
			return;
		}

		e.preventDefault();


		for (let i = 0; i < files.length; i += 1) {
			this.handler.handle(files[i], this).catch(() => {

			});
		}
	};

}



